﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

using ScintillaNet;
using EditControl;


namespace IHMainApp
{
	public partial class frmDocument : TabPage
	{
		private string _filePath = null;
		public string FilePath
		{
			get { return _filePath; }
			set
			{
				_filePath = value;
			}
		}
        
		public frmDocument()
		{
			InitializeComponent();
            //EditControl.AddError("frmDocument.cs - line 32, col 61 - Remove it if you want :) - points to (2, 2)", 2, 2);
		}

        private void sciDocument_SavePointReached(object sender, EventArgs e)
        {
            addOrRemoveAsteric();
        }

        private void sciDocument_SavePointLeft(object sender, EventArgs e)
        {
            addOrRemoveAsteric();
        }

        private void addOrRemoveAsteric()
        {

                if (this.Document.IsDirty)
                {
                    if (!this.Text.EndsWith(" *"))
                        this.Text += " *";
                }
                else
                {
                    if (this.Text.EndsWith(" *"))
                        this.Text = Text.Substring(0, this.Text.Length - 2);
                }
        }

		public Scintilla Document
		{
			get
			{
                return EditControl;
			}
		}

        

		public bool Save()
		{
			if (String.IsNullOrEmpty(_filePath))
				return SaveAs();

			return save(_filePath);
		}

		public bool SaveAs()
		{
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				_filePath = saveFileDialog.FileName;
				return save(_filePath);
			}
			else
			{
				return false;
			}
		}

		private bool save(string path)
		{
			using (FileStream fs = File.Create(path))
			using (BinaryWriter bw = new BinaryWriter(fs))
                bw.Write(EditControl.RawText, 0, EditControl.RawText.Length - 1); // Omit trailing NULL

            EditControl.IsDirty = false;
			return true;
		}
  	}
}
